//
//  MOChangePasswordViewController.m
//  MobileOffice
//
//  Created by 冰冰 on 2019/6/2.
//  Copyright © 2019 com.idolmedia. All rights reserved.
//

#import "MOChangePasswordViewController.h"
#import "MOChangePasswordViewCell.h"

@interface MOChangePasswordViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UIImageView *headerView;

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataArray;

@end

@implementation MOChangePasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatView];
    
    [self initData];
}

-(void)creatView
{
    self.title = @"密码修改";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.tableHeaderView = self.headerView;
}


-(void)initData
{
    self.dataArray = [NSMutableArray array];
    NSArray *nameArr = @[@"原密码",@"新密码",@"确认密码",@"短信验证"];
    NSArray *paleArr = @[@"请输入原密码",@"请输入新密码",@"请输入再次输入密码",@"请输入短信验证码"];
    for (int i = 0; i<4; i++) {
        MOChangePasswordModel *model = [[MOChangePasswordModel alloc]init];
        model.nameStr = nameArr[i];
        model.placeStr = paleArr[i];
        if (i==3) {
            model.type = @"1";
        }else{
            model.type = @"0";
        }
        [self.dataArray addObject:model];
    }
    [self.tableView reloadData];
}

#pragma mark -- 获取验证码
- (void)getTelCode
{
    MOUser *user = [MOUser sharedMOUser];
    
    NSString *postUrl = [NSString stringWithFormat:@"%@/%@/%@",A_CAPTCHA_URL,@"MODIFYPWD",user.userName];
    
    [PPNetworkHelper GET:postUrl parameters:@{} success:^(id responseObject) {
        NSLog(@"获取验证码:%@",responseObject);
        
        if ([responseObject integerValue]==0) {
            [[ADShowMessage shareShowMessage] showTextOnly:@"发送成功" showInView:self.view];
        }else if ([responseObject integerValue]==1){
            [[ADShowMessage shareShowMessage] showTextOnly:@"发送异常" showInView:self.view];
        }else if ([responseObject integerValue]==2){
            [[ADShowMessage shareShowMessage] showTextOnly:@"用户不存在" showInView:self.view];
        }else if ([responseObject integerValue]==3){
            [[ADShowMessage shareShowMessage] showTextOnly:@"用户为注册手机号码" showInView:self.view];
        }else{
            [[ADShowMessage shareShowMessage] showTextOnly:@"短信接口调用异常" showInView:self.view];
        }
        
    } failure:^(NSError *error) {
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:WINDOW];
    }];
}

#pragma mark -- 确认修改
-(void)sureSaveSet
{
    
    MOChangePasswordViewCell *cell0 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    
    MOChangePasswordViewCell *cell1 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    
    MOChangePasswordViewCell *cell2 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
    
    MOChangePasswordViewCell *cell3 = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:0]];
    
    if (cell0.textField.text.length==0) {
        [[ADShowMessage shareShowMessage] showTextOnly:@"输入旧密码" showInView:self.view];
        return;
    }
    if (cell1.textField.text.length==0) {
        [[ADShowMessage shareShowMessage] showTextOnly:@"输入新密码" showInView:self.view];
        return;
    }
    if (cell2.textField.text.length==0) {
        [[ADShowMessage shareShowMessage] showTextOnly:@"输入确认的新密码" showInView:self.view];
        return;
    }
    if (cell3.textField.text.length==0) {
        [[ADShowMessage shareShowMessage] showTextOnly:@"输入验证码" showInView:self.view];
        return;
    }
    
    MOUser *user = [MOUser sharedMOUser];
    NSString *oldPassword = [self sha1:[NSString stringWithFormat:@"%@%@",cell0.textField.text,user.userName]];
    if (![user.password isEqualToString:oldPassword]) {
        [[ADShowMessage shareShowMessage] showTextOnly:@"输入的旧密码有误" showInView:self.view];
        return;
    }
    
    if (![cell1.textField.text isEqualToString:cell2.textField.text]) {
        [[ADShowMessage shareShowMessage] showTextOnly:@"两次输入的密码不一样" showInView:self.view];
        return;
    }
    
    NSDictionary *parameters = @{
                           @"userName":user.userName,
                           @"password":[self sha1:[NSString stringWithFormat:@"%@%@",cell1.textField.text,user.userName]]
                           };
    
    NSString *postUrl = [NSString stringWithFormat:@"%@/%@",RESETPASSWORD_URL,cell3.textField.text];
    
    [[ADShowMessage shareShowMessage] showHUDAddedTo:self.view animated:YES];
    
    [PPNetworkHelper POST:postUrl parameters:parameters success:^(id responseObject) {
        NSLog(@"修改密码:%@",responseObject);
        
        [[ADShowMessage shareShowMessage] hideHUDForView:self.view animated:YES];
        
        if ([responseObject[@"code"] integerValue]==1) {//0：接口异常 1：接口正常

            [[ADShowMessage shareShowMessage] showTextOnly:@"修改密码成功，请重新登录" showInView:self.view];
            [self performSelector:@selector(outLoginA) withObject:nil afterDelay:1];
            
        }else{
            [[ADShowMessage shareShowMessage] showTextOnly:responseObject[@"msg"] showInView:self.view];
        }
    } failure:^(NSError *error) {
        [[ADShowMessage shareShowMessage] hideHUDForView:self.view animated:YES];
        
        [[ADShowMessage shareShowMessage] showTextOnly:[error localizedDescription] showInView:self.view];
    }];
    
}


-(void)outLoginA
{
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate outLogin];//创建tabbar
    [MOUser clearUser];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return self.dataArray.count;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        MOChangePasswordViewCell *setCell = [MOChangePasswordViewCell cellWithTableView:tableView andIndexPath:indexPath];
        if (indexPath.row!=3) {
            setCell.textField.secureTextEntry = YES;
        }else{
            setCell.textField.secureTextEntry = NO;
        }
        __weak typeof (self)weakSelf = self;
        setCell.clickCodeBlock = ^{
            [weakSelf getTelCode];
        };
        setCell.model = self.dataArray[indexPath.row];
        return setCell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
            cell.textLabel.text = @"保存当前设置";
            cell.textLabel.font = FONT_SIZE(15);
            cell.textLabel.textColor = KBlueColor_2C94FF;
        }
        return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return kHConversions(73);
    }else{
        return kHConversions(54);
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 10;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 0.0000001;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1) {
        [self sureSaveSet];
    }
}

#pragma mark - 设置顶头分割线
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        if (@available(iOS 8.0, *)) {
            [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        if (@available(iOS 8.0, *)) {
            [cell setLayoutMargins:UIEdgeInsetsMake(0, 0, 0, 0)];
        } else {
            // Fallback on earlier versions
        }
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }
}

#pragma mark -//sha1加密方式
- (NSString *) sha1:(NSString *)input
{
    //这两句容易造成 、中文字符串转data时会造成数据丢失
    //const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    //NSData *data = [NSData dataWithBytes:cstr length:input.length];
    //instead of
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

#pragma mark -- 懒加载
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-StatusBarAndNavigationBarHeight-TabbarSafeBottomMargin) style:UITableViewStyleGrouped];
        _tableView.separatorColor = KGrayColor_ededed;
        _tableView.backgroundColor = KGrayColor_f8f8f8;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

-(UIImageView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 152)];
        CGFloat scale = 303.0/749.0;
        _headerView.height = scale*SCREEN_WIDTH;
        _headerView.backgroundColor = [UIColor whiteColor];
        _headerView.image = IMAGE(@"setPasswordBack");
        
        UIView *labelView = [[UIView alloc]initWithFrame:CGRectMake(14, 0, SCREEN_WIDTH - 111 - 28 - 33, 1)];
        [_headerView addSubview:labelView];
        
        UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, labelView.width, 1)];
        label1.height = [NSString labelAutoCalculateRectWith:@"为了您的账号安全，请您妥善保管好您的密码" WithFont:[UIFont boldSystemFontOfSize:18] MaxSize:CGSizeMake(labelView.width, MAXFLOAT)].height;
        label1.text = @"为了您的账号安全，请您妥善保管好您的密码";
        label1.numberOfLines = 0;
        label1.textColor = KBlackColor_222222;
        label1.font = [UIFont boldSystemFontOfSize:18];
        [labelView addSubview:label1];
        
        UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(0, label1.bottom + 11, labelView.width, 1)];
        label2.height = [NSString labelAutoCalculateRectWith:@"设置多种身份验证是提升账号安全的最佳方法，忘记密码、丢失手机时可快速找回账号确保您的账号安全" WithFont:FONT_SIZE(11) MaxSize:CGSizeMake(labelView.width, MAXFLOAT)].height;
        label2.text = @"设置多种身份验证是提升账号安全的最佳方法，忘记密码、丢失手机时可快速找回账号确保您的账号安全";
        label2.numberOfLines = 0;
        label2.textColor = KGrayColor_BABEC2;
        label2.font = FONT_SIZE(11);
        [labelView addSubview:label2];
        
        labelView.height = label1.height + label2.height + 11;
        labelView.centerY = _headerView.height/2;
        
        
    }
    return _headerView;
}


@end
